package cn.phecda.boot.data.jpa.util;

import cn.phecda.boot.common.lang.constants.SymbolConsts;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;

/**
 * <p> Jpa工具 </p>
 *
 * @author : wanpinwei
 */
public class JpaUtils {
    private static Join<?, ?> join(From<?, ?> from, String attribute, JoinType joinType) {
        for (Join<?, ?> join : from.getJoins()) {
            boolean sameName = join.getAttribute().getName().equals(attribute);
            if (sameName && join.getJoinType().equals(joinType)) {
                return join;
            }
        }
        return from.join(attribute, joinType);
    }

    public static Join<?, ?> innerJoin(From<?, ?> from, String attribute) { 
        return join(from, attribute, JoinType.INNER);
    }

    public static Join<?, ?> leftJoin(From<?, ?> from, String attribute) { 
        return join(from, attribute, JoinType.LEFT);
    }

    public static Join<?, ?> rightJoin(From<?, ?> from, String attribute) { 
        return join(from, attribute, JoinType.RIGHT);
    }

    public static String like(String property) {
        return SymbolConsts.PERCENT + property + SymbolConsts.PERCENT;
    }

}
